package com.alvin.mbp.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alvin.mbp.dao.GoodsDao;
import com.alvin.mbp.dao.MarchandiseDao;
import com.alvin.mbp.dao.PointMemberDao;
import com.alvin.mbp.dao.PointRecordDao;
import com.alvin.mbp.dao.QrGoodsCodeDao;
import com.alvin.mbp.entity.Goods;
import com.alvin.mbp.entity.Marchandise;
import com.alvin.mbp.entity.PointMember;
import com.alvin.mbp.entity.PointRecord;
import com.alvin.mbp.entity.PointType;
import com.alvin.mbp.entity.QrGoodsCode;

@Service
@Transactional
public class PointService {

	@Autowired
	private QrGoodsCodeDao qrGoodsCodeDao;

	@Autowired
	private GoodsDao goodsDao;

	@Autowired
	private MarchandiseDao marchandiseDao;

	@Autowired
	private PointRecordDao pointRecordDao;

	@Autowired
	private PointMemberDao pointMemberDao;

	/**
	 * 根据积分码查询有效性，并得到相关信息
	 * 
	 * @param iCode
	 * @return
	 */
	public Map<String, Object> searchPointGoods(String iCode) {
		Map<String, Object> qrMap = new HashMap<String, Object>();
		QrGoodsCode qr = qrGoodsCodeDao.findByPropertyOne("i_code", iCode);
		qrMap.put("iCode", iCode);
		if (qr != null && !qr.getState().equals("已积分")) {
			qrMap.put("q", qr);
			// 省代已经出库的就可以积分
			String sql = "SELECT * FROM GOODS GO LEFT JOIN QR_GOODS_CODE QR ON GO.QR_CODE_ID = QR.ID WHERE QR_CODE_ID = ? AND QR.STATE != ? AND DEPARTMENT_ID IN (SELECT ID FROM DEPARTMENT WHERE TYPE_ID >= (SELECT ID FROM DEPARTMENT_TYPE WHERE NAME = ?)) ORDER BY QR.`INSERT_TIME`";
			Object[] params = { qr.getId(), "已积分", "省代" };
			List<Goods> goodsList = goodsDao.findBySql(sql, params);
			for (Goods g : goodsList) {
				qrMap.put("g", g);
				Marchandise m = marchandiseDao.findById(g.getMarchandiseId());
				qrMap.put("m", m);
				break;
			}

		}
		return qrMap;
	}

	/**
	 * 用户在线积分
	 * 
	 * @param qrId
	 * @param qrPoint
	 * @param iCode
	 * @param member
	 * @return
	 */
	public boolean charge(Integer qrId, double qrPoint, String iCode, PointMember member) {
		try {
			// 保存积分记录
			PointRecord record = new PointRecord();
			record.setMemberId(member.getId());
			record.setiCode(iCode);
			record.setOper(PointType.POINT_WAP.getValue());
			record.setType(PointType.POINT_WAP.ordinal());
			record.setPoint(qrPoint);
			member = pointMemberDao.findById(member.getId());
			double balance = member.getBalance() + qrPoint;
			record.setBalance(balance);
			pointRecordDao.save(record);
			// 更新二维码的状态为已积分
			qrGoodsCodeDao.updateByID(qrId, "state", "已积分");
			// 更新用户的积分余额
			pointMemberDao.updateByID(member.getId(), "balance", balance);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
